<template>
  <div class="avatar-upload">
    <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="uploadHeaders"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
    <div class="upload-tips">
      <p>点击上传头像</p>
      <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 2 // MB
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const imageUrl = ref(props.modelValue)

const uploadUrl = computed(() => {
  return import.meta.env.VITE_API_BASE_URL + '/upload/avatar' || '/api/upload/avatar'
})

const uploadHeaders = computed(() => {
  const token = getToken()
  return token ? { Authorization: `Bearer ${token}` } : {}
})

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < props.size

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error(`上传头像图片大小不能超过 ${props.size}MB!`)
    return false
  }
  return true
}

const handleSuccess = (response) => {
  if (response.code === 200) {
    imageUrl.value = response.data.url
    emit('update:modelValue', response.data.url)
    emit('success', response.data.url)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleError = (error) => {
  console.error('Upload error:', error)
  ElMessage.error('上传失败，请重试')
}

// 模拟上传成功（开发时使用）
const mockUpload = () => {
  const mockUrl = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  setTimeout(() => {
    handleSuccess({
      code: 200,
      data: { url: mockUrl }
    })
  }, 1000)
}

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  imageUrl.value = newVal
})
</script>

<style lang="scss" scoped>
.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.upload-tips {
  margin-top: 10px;
  
  p {
    margin: 5px 0;
    font-size: 12px;
    color: #999;
    
    &:first-child {
      color: #666;
      font-size: 14px;
    }
  }
}
</style>
